// pages/publish/publish.js
Page({
  data: {
    userInfo: null,
    phone: '',
    title: '',
    text: '',
    imagePaths: [],
    topicType: '',
    topicTypes: [
      '党史学习',
      '革命故事',
      '红色记忆',
      '革命精神',
      '红色旅游',
      '其他分类'
    ]
  },

  onLoad() {
    this.checkLoginStatus();
  },

  // 检查登录状态
  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo');
    const phone = wx.getStorageSync('phone');
    
    if (!userInfo) {
      wx.showModal({
        title: '提示',
        content: '请先登录账号',
        confirmText: '去登录',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/mine/mine'
            });
          } else {
            wx.navigateBack();
          }
        }
      });
      return;
    }
    
    this.setData({
      userInfo: userInfo,
      phone: phone || ''
    });
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  },

  // 标题输入
  onTitleInputChange(e) {
    this.setData({
      title: e.detail.value
    });
  },

  // 内容输入
  onTextInputChange(e) {
    this.setData({
      text: e.detail.value
    });
  },

  // 选择图片
  chooseImage() {
    if (this.data.imagePaths.length >= 9) {
      wx.showToast({
        title: '最多上传9张图片',
        icon: 'none'
      });
      return;
    }
    
    wx.chooseImage({
      count: 9 - this.data.imagePaths.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          imagePaths: [...this.data.imagePaths, ...res.tempFilePaths]
        });
      }
    });
  },

  // 删除图片
  removeImage(e) {
    const index = e.currentTarget.dataset.index;
    const newImagePaths = [...this.data.imagePaths];
    newImagePaths.splice(index, 1);
    this.setData({
      imagePaths: newImagePaths
    });
  },

  // 显示分类选择器
  showTopicTypePicker() {
    this.setData({
      showPicker: true
    });
  },

  // 分类选择变化
  onTopicTypeChange(e) {
    const index = e.detail.value;
    this.setData({
      topicType: this.data.topicTypes[index]
    });
  },

  // 上传图片到云存储
  async uploadImages() {
    const uploadTasks = this.data.imagePaths.map((path, index) => {
      const cloudPath = `topic_images/${Date.now()}-${index}.jpg`;
      return wx.cloud.uploadFile({
        cloudPath,
        filePath: path
      });
    });
    
    try {
      const results = await Promise.all(uploadTasks);
      return results.map(res => res.fileID);
    } catch (err) {
      console.error('图片上传失败:', err);
      throw err;
    }
  },

  // 保存话题
  async saveTopic() {
    if (!this.data.title || !this.data.text) {
      wx.showToast({
        title: '标题和内容不能为空',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({
      title: '发布中...',
      mask: true
    });
    
    try {
      // 上传图片
      let imageUrls = [];
      if (this.data.imagePaths.length > 0) {
        imageUrls = await this.uploadImages();
      }
      
      // 保存到数据库
      const db = wx.cloud.database();
      await db.collection('topics').add({
        data: {
          title: this.data.title,
          content: this.data.text,
          images: imageUrls,
          type: this.data.topicType || '其他分类',
          author: {
            avatarUrl: this.data.userInfo.avatar,
            nickName: this.data.userInfo.username,
            phone: this.data.userInfo.phone
          },
          createTime: db.serverDate(),
          viewCount: 0,
          likeCount: 0,
          commentCount: 0
        }
      });
      
      wx.hideLoading();
      wx.showToast({
        title: '发布成功',
        icon: 'success'
      });
      
      // 返回并刷新上一页
      const pages = getCurrentPages();
      if (pages.length > 1) {
        const prevPage = pages[pages.length - 2];
        if (prevPage.onShow) {
          prevPage.onShow();
        }
      }
      
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      
    } catch (err) {
      console.error('发布失败:', err);
      wx.hideLoading();
      wx.showToast({
        title: '发布失败',
        icon: 'none'
      });
    }
  }
});